
package com.nd.rj.common.login.atomoperation;

import android.database.Cursor;
import android.util.Log;

import com.nd.rj.common.R;
import com.nd.rj.common.login.dbreposit.CfgDBHelper;
import com.nd.rj.common.util.db.IDataBaseRef;
import com.product.android.business.ApplicationVariable;
import com.product.android.business.bean.UserInfo;

/**
 * 用户信息表原子操作
 * 
 * @author yiyang
 */
public class OperUserInfo {

    /**不要直接使用，调用getDBHelper()以获取最新值，因为其有可能被回收*/
    private IDataBaseRef mDBHelper;

    private static OperUserInfo mAtom;

    public OperUserInfo() {
        getDBHelper();
    }

    public static OperUserInfo getInstance() {
        if (mAtom == null)
            mAtom = new OperUserInfo();
        return mAtom;
    }
    
    private IDataBaseRef getDBHelper(){
        mDBHelper = CfgDBHelper.getInstance();

        // 如果DB帮助类已经，这里重新打开
        if (!mDBHelper.DbValid()) {
            mDBHelper = CfgDBHelper.getInstance();
            mDBHelper.open(ApplicationVariable.INSTANCE.applicationContext, null);
        }
        
        return mDBHelper;
    }

    public int SetUserInfo(UserInfo userinfo) {
        int ireturn = R.string.nd_set_user_info_error;
        String password = userinfo.getUserPass();
        StringBuilder sb = new StringBuilder();
        sb.append("INSERT OR REPLACE INTO USERINFO([UAP_UID],[USER_NAME],[USER_NICK_NAME],[USER_PASS],");
//        sb.append("[USER_PASS_MD5],[OAP_UNIT_ID],[OAP_UID],[ISSAVEACCOUNT],[ISAUTOLOGIN],[LAST_LOGIN_DT],[VAR_EXT],[ISPHONE])");
        sb.append("[USER_PASS_MD5]," +
        		  "[USER_PASS_MIXED_MD5]," +
        		  "[BLOWFISH]," +
        		  "[TICKET]," +
        		  "[ISADMIN]," +
        		  "[OAP_UNIT_ID]," +
        		  "[OAP_UID]," +
        		  "[ISSAVEACCOUNT]," +
        		  "[ISAUTOLOGIN]," +
        		  "[LAST_LOGIN_DT]," +
        		  "[VAR_EXT]," +
        		  "[sex]," +
        		  "[prestige]," +
        		  "[wealth]," +
        		  "[grade]," +
        		  "[flower]," +
        		  "[realname]," +
        		  "[uniquename]," +
        		  "[ISPHONE])");
        sb.append(" VALUES(");
        sb.append("").append(userinfo.getUapUid()).append(",");
        sb.append("'").append(userinfo.getUserName()).append("',");
        sb.append("'").append(CfgDBHelper.quotedString(userinfo.getUserNickName())).append("',");
        sb.append("'").append(CfgDBHelper.quotedString(password)).append("',");
        sb.append("'").append(userinfo.getUserPassMd5()).append("',");
        sb.append("'").append(userinfo.getUserPassMixedMd5()).append("',");
        sb.append("'").append(userinfo.getBlowfish()).append("',");
        sb.append("'").append(userinfo.getTicket()).append("',");
        sb.append("'").append(userinfo.getIsAdmin()).append("',");
        sb.append("").append(userinfo.getOapUnitId()).append(",");
        sb.append("").append(userinfo.getOapUid()).append(",");
        sb.append("'").append(String.format("%b", userinfo.getIsSaveAccount())).append("',");
        sb.append("'").append(String.format("%b", userinfo.getIsAutoLogin())).append("',");
        sb.append("(select julianday(ifnull(max(LAST_LOGIN_DT), 0)) + 1 from userinfo),");
        sb.append("'").append(userinfo.getmVar_ext()).append("',");
        
        sb.append("").append(userinfo.sex).append(",");
        sb.append("").append(userinfo.prestige).append(",");
        sb.append("").append(userinfo.wealth).append(",");
        sb.append("").append(userinfo.grade).append(",");
        sb.append("").append(userinfo.flower).append(",");
        
        sb.append("'").append(userinfo.realname).append("',");
        sb.append("'").append(userinfo.uniquename).append("',");
        
        sb.append("").append(userinfo.getIs_phone()).append(")");
        /*用时间有个问题，如果系统时间改来改去就有问题了*/
        //sb.append("datetime(CURRENT_TIMESTAMP,'localtime'))");
        ireturn = getDBHelper().execSql(sb.toString());
        return ireturn;
    }
    
    /**
     *  设置扩展字段的值
     * @param uap_uid
     * @param var_ext
     * @return
     */
  
    public int setExtInfo(long uap_uid, String var_ext) {
        int ireturn = R.string.nd_set_user_info_error;
        StringBuilder sb = new StringBuilder();
        sb.append(" update USERINFO set VAR_EXT = '" 
        		+ var_ext +"' "
        		+" where uap_uid = "+uap_uid);
        ireturn = getDBHelper().execSql(sb.toString());
        return ireturn;
    }
    

    /**
     * 获取用户信息
     * 
     * @param user_id
     * @return
     */
    public UserInfo GetUserInfo(long user_id) {
        UserInfo user = new UserInfo();
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT * FROM USERINFO");
        if (user_id > 0)
            sb.append(String.format(" WHERE USER_ID=%d ", user_id));
        else
            sb.append(" order by LAST_LOGIN_DT desc limit 1;");
        Cursor cur = getDBHelper().querySql(sb.toString());
        try {
            if ((cur != null) && (cur.getCount() > 0)) {
                cur.moveToFirst();
                user.LoadFormCursor(cur);
            }
        } finally {
            CfgDBHelper.closeCursor(cur);
        }
        return user;
    }

    public UserInfo GetLastUserInfo() {
        return GetUserInfo(0);
    }
    
    /**
     * <br>Description:TODO 保存最后一次登录后的组织ID
     * <br>Author:daiyf
     * <br>Date:2013-6-5下午2:29:47
     * @param unitid
     * @param oap_uid
     */
    public void UpdateLastUserInfo(long unitid, long oap_uid) {
        UserInfo user = new UserInfo();
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT * FROM USERINFO");
        sb.append(" order by LAST_LOGIN_DT desc limit 1;");
        Cursor cur = getDBHelper().querySql(sb.toString());
        try {
            if ((cur != null) && (cur.getCount() > 0)) {
                cur.moveToFirst();
                user.LoadFormCursor(cur);
            }
        } finally {
            CfgDBHelper.closeCursor(cur);
        }

        if(user.getOapUid() != oap_uid || user.getOapUnitId() != unitid){
            String str = " update USERINFO set OAP_UNIT_ID=" 
            		+ unitid +", OAP_UID=" + oap_uid
            		+" where uap_uid = "+user.getUapUid();
            int ret = getDBHelper().execSql(str);
            if(ret != 0){
            	Log.e("NdCommonLibs", "UpdateLastUserInfo error");
            }
        }        
    }

    /**
     * 根据登录名获取用户信息
     * 
     * @param userName
     * @return
     */
    public UserInfo GetUserByUserName(String userName) {
        UserInfo user = null;
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT * FROM USERINFO");
        sb.append(" WHERE USER_NAME='" + userName + "' ");
        Cursor cur = getDBHelper().querySql(sb.toString());
        try {
            if ((cur != null) && (cur.getCount() > 0)) {
                user = new UserInfo();
                cur.moveToFirst();
                user.LoadFormCursor(cur);
            }
        } finally {
            CfgDBHelper.closeCursor(cur);
        }
        return user;
    }

    /**
     * @n<b>删除用户</b> :DeleteUserInfo
     * @brief
     * @see
     * @param @param uap_uid
     * @param @return
     * @return int
     * @<b>作者</b> : yanyy
     * @<b>创建时间</b> : 2011-10-14下午07:36:22
     */
    public int DeleteUserInfo(long uap_uid) {
        StringBuilder sb = new StringBuilder();
        sb.append("delete from USERINFO where UAP_UID=").append(uap_uid);
        return getDBHelper().execSql(sb.toString());
    }
    
    
    /**
     * @Title: deleteAllUsers  
     * @Description: TODO(删除所有用户)  
     * @author yanyy
     * @date 2012-11-12 上午10:41:15 
     *
     * @return       
     * @return int
     * @throws
     */
    public int deleteAllUsers() {
        StringBuilder sb = new StringBuilder();
        sb.append("delete from USERINFO");
        return getDBHelper().execSql(sb.toString());
    }
    
    /**
     * @Title: clearUserPassWord  
     * @Description: TODO(清除密码)  
     * @author yanyy
     * @date 2012-11-12 上午11:03:18 
     *
     * @param uap_uid
     * @return       
     * @return int
     * @throws
     */
    public int clearUserPassWord(long uap_uid){
        StringBuilder sb = new StringBuilder();
        sb.append("update USERINFO set ISSAVEACCOUNT = '").append(String.format("%b", false)).append("', ");
        sb.append(" USER_PASS = '' where UAP_UID=").append(uap_uid);
        return getDBHelper().execSql(sb.toString());
    }
    
    /**
     * 清除用户保存密码标记
     * @n<b>函数名称</b>     :clearUserSaveCount
     * @brief
     * @see
     * @since    Ver 1.1
     * @param  @param uap_uid
     * @param  @return
     * @return int
     * @<b>作者</b>          :  黄永鑫
     * @<b>创建时间</b>      :  2014-1-10上午11:39:45
     */
    public int clearUserSaveCount(long uap_uid){
        StringBuilder sb = new StringBuilder();
        sb.append("update USERINFO set ISSAVEACCOUNT = '").append(String.format("%b", false))
        .append(" where UAP_UID=").append(uap_uid);
        return getDBHelper().execSql(sb.toString());
    }

}
